#include<unordered_map>
#include<list>
using namespace std;
class LRUCache {
private:
    struct Node {
        int key;
        int value;
        Node* prev=nullptr;
        Node* next=nullptr;
        Node(int key_, int value_):key(key_), value(value_) {

        }
    };

    void Push(Node* node) {
        last->next = node;
        node->prev = last;
        last = node;
    }

    void Remove(Node* node) {
        node->prev->next = node->next;
        if (node->next)
            node->next->prev = node->prev;
        else
            last = node->prev;
        node->next = nullptr;
        node->prev = nullptr;
    }

    Node* head, * last;
    int capacity;
    unordered_map<int, Node*> map;

public:
    LRUCache(int capacity):capacity(capacity){
        head = new Node(-1,-1);
        last = head;
        head->next = last;
        last->prev = head;
    }

    int get(int key) {
        int res = -1;
        if (map.find(key) != map.end()) {
            Node* node = map[key];
            res = node->value;
            Remove(node);
            Push(node);
        }
        return res;
    }

    void put(int key, int value) {
        Node* node = nullptr;
        auto it = map.find(key);
        if (it != map.end()) {
            node = it->second;
            node->value = value;
            Remove(node);
        }
        else {
            if (map.size() == capacity) {
                node = head->next;
                Remove(node);
                map.erase(map.find(node->key));
                node->key = key;
                node->value = value;
            }
            else
                node = new Node(key, value);
            map[key] = node;
        }
        Push(node);
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */